require 'domain_exception.rb'

class UsersController < ApplicationController
  before_filter :check_authentication, :except => [:signin, :signout, :signup, :list]
  
  def list
    @initial = params[:initial]
    @users = User.find_by_initial(@initial)
  end
  
  def signin
    if request.post?
      session[:user] = User.authenticate(params[:username], params[:password]).id
      if session[:intended_controller].nil?
        redirect_to :controller => "identities"
      else
        redirect_to :controller => session[:intended_controller], :action => session[:intended_action]
      end
    end
  rescue AuthenticationFailureException => e
    flash[:notice] = e.message
    redirect_to :action => 'signin'
  end  
  
  def signout
    session[:user] = nil
    redirect_to :action => :signin
  end
  
  def signup
    if request.post?
      @user = User.new(params[:user])
      @user.save!
      session[:user] = @user.id
      redirect_to :controller => "identities"
    end
  rescue ActiveRecord::RecordInvalid 
    render
  end
  
  def change_password
    if request.post?
      @user.change_password(params[:old_password], params[:new_password])
      flash[:notice] = "密码修改成功！"
    end
  rescue Exception => e
    flash[:notice] = "密码修改失败！"
  end
  
  def invite
    if request.post?
      raise IllegalParameterException.new('请输入被邀请人的Email地址') if params[:email].blank?
      raise IllegalParameterException.new('Email地址不合法') unless params[:email] =~ User::EMAIL_FORMAT_PATTERN
      
      Invitation.deliver_invite(User.find(session[:user]), params[:email])
      flash[:notice] = '您已经成功发送了邀请给您的朋友'
    end
  rescue IllegalParameterException => e
    flash[:error] = e.message
    redirect_to
  end
end